import { reactive, ref, watch, watchEffect } from '@vue/composition-api';

export function useUser() {
  const state = ref<'unlogged' | 'logged' | 'logging'>('unlogged');

  const user = reactive({
    name: '',
    login: false,
    token: '',
    avatar: '',
  });

  const login = () => {
    console.log('开始登入');
    state.value = 'logging';
    setTimeout(() => {
      state.value = 'logged';
      user.name = 'swq';
      user.login = true;
      user.token = '11012341234';
      user.avatar =
        'https://interest-image-dev.billbear.cn/dev/GOODS/tn-iEEAi-2tPTbMjX9CmotygqJ55YAx_08-x4WrFFPs=@big_jpg';
    }, 3000);
  };

  watchEffect(() => {
    console.log('user update todo sth', user.name);
    localStorage.setItem('TOKEN', user.token);
  });

  watch(state, s => {
    if (s === 'unlogged') {
      console.log('用户退出');
      return;
    }

    if (s === 'logged') {
      console.log('用户登入');
      return;
    }
  });

  return {
    user: user,
    login: login,
    state: state,
  };
}
